<template>
  <div class="p-4">
    <div class="flex justify-between items-center mb-4">
      <h1 class="text-2xl font-bold text-slate-800 ">任务视图</h1>
      <div class="space-x-2">
        <el-button @click="reload" :loading="loading">刷新</el-button>
      </div>
    </div>

    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" :model="query">
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable style="width: 140px">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item label="统计天数">
          <el-select v-model="query.days" placeholder="7天" style="width: 120px">
            <el-option :value="7" label="近7天" />
            <el-option :value="14" label="近14天" />
            <el-option :value="30" label="近30天" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reload" :loading="loading">
            <el-icon class="mr-1"><Search /></el-icon>搜索
          </el-button>
          <el-button @click="reset">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">任务列表</div>
        </div>
      </template>
      <el-table :data="rows" v-loading="loading" border style="width: 100%">
        <el-table-column prop="taskType" label="类型" width="100" />
        <el-table-column prop="name" label="名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fetchTime" label="抓取时间" width="120" />
        <el-table-column prop="lastFetchAt" label="上次抓取时间" width="180" />
        <el-table-column prop="errorCount" label="错误次数" width="100" />
        <el-table-column prop="fetchCount" label="抓取次数" width="100" />
        <el-table-column label="成功率" width="140">
          <template #default="scope">
            <div v-if="scope.row.successRate !== undefined" class="space-y-1">
              <div class="flex items-center space-x-2">
                <div class="relative w-6 h-6">
                  <svg class="w-6 h-6 transform -rotate-90" viewBox="0 0 24 24">
                    <!-- 背景圆环 -->
                    <circle cx="12" cy="12" r="8" stroke="#e5e7eb" stroke-width="3" fill="none"/>
                    <!-- 进度圆环 -->
                    <circle cx="12" cy="12" r="8" 
                            stroke="currentColor" 
                            stroke-width="3" 
                            fill="none"
                            stroke-linecap="round"
                            :stroke-dasharray="`${2 * Math.PI * 8}`"
                            :stroke-dashoffset="`${2 * Math.PI * 8 * (1 - scope.row.successRate / 100)}`"
                            :style="{color: getSuccessRateColor(scope.row.successRate)}"/>
                  </svg>
                </div>
                <span class="text-sm">{{ scope.row.successRate }}%</span>
              </div>
            </div>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="有效率" width="140">
          <template #default="scope">
            <div v-if="scope.row.effectiveSuccessRate !== undefined" class="space-y-1">
              <div class="flex items-center space-x-2">
                <div class="relative w-6 h-6">
                  <svg class="w-6 h-6 transform -rotate-90" viewBox="0 0 24 24">
                    <!-- 背景圆环 -->
                    <circle cx="12" cy="12" r="8" stroke="#e5e7eb" stroke-width="3" fill="none"/>
                    <!-- 进度圆环 -->
                    <circle cx="12" cy="12" r="8" 
                            stroke="currentColor" 
                            stroke-width="3" 
                            fill="none"
                            stroke-linecap="round"
                            :stroke-dasharray="`${2 * Math.PI * 8}`"
                            :stroke-dashoffset="`${2 * Math.PI * 8 * (1 - scope.row.effectiveSuccessRate / 100)}`"
                            :style="{color: getSuccessRateColor(scope.row.effectiveSuccessRate)}"/>
                  </svg>
                </div>
                <span class="text-sm">{{ scope.row.effectiveSuccessRate }}%</span>
              </div>
            </div>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <span class="mr-2">
              <el-button size="small" circle type="primary" plain @click="handleTrigger(scope.row)" aria-label="手动触发">
                <el-icon><Position /></el-icon>
              </el-button>
            </span>
            <el-button size="small" text @click="goEdit(scope.row)">编辑源</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="reload"
          @current-change="reload"
        />
      </div>
    </el-card>
  </div>
  
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Position } from '@element-plus/icons-vue'
import { fetchTaskAPI } from '@/services/api'

definePageMeta({ layout: 'admin' })

const loading = ref(false)
const rows = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = ref({ status: undefined, days: 7 })

const reload = async () => {
  loading.value = true
  try {
    const data = await fetchTaskAPI.getPageWithSuccessRate({ 
      pageNum: pageNum.value, 
      pageSize: pageSize.value, 
      status: query.value.status,
      days: query.value.days
    })
    rows.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const reset = () => {
  query.value = { status: undefined, days: 7 }
  pageNum.value = 1
  reload()
}

// 获取成功率颜色映射（连续渐变）
const getSuccessRateColor = (rate) => {
  // 使用HSL颜色空间，从红色(0°)到绿色(120°)的连续渐变
  // 0% = 红色, 50% = 黄色, 100% = 绿色
  const hue = (rate / 100) * 120 // 0-120度
  const saturation = 70 // 固定饱和度
  const lightness = 50 // 固定亮度
  
  return `hsl(${hue}, ${saturation}%, ${lightness}%)`
}

const goEdit = (row) => {
  // 仅支持 RSS 当前实现
  if (row.taskType === 'RSS' && row.feedId) {
    navigateTo(`/admin/fetch/rss/edit/${row.feedId}`)
  }
}

const handleTrigger = async (row) => {
  try {
    await ElMessageBox.confirm(`确认立即触发【${row.name}】的抓取？`, '提示', { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' })
    
    // 调用后端异步触发接口
    const data = await fetchTaskAPI.trigger(row.feedId)
    const taskId = data.taskId
    ElMessage.success(data.message || '抓取任务已提交，正在后台执行')
    
    // 轮询查询任务状态
    await pollTaskStatus(taskId, row.name)
    
    // 刷新列表
    reload()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('触发抓取任务失败')
    }
  }
}

// 轮询查询任务状态
const pollTaskStatus = async (taskId, taskName) => {
  const maxAttempts = 30 // 最多轮询30次
  const interval = 2000 // 每2秒查询一次
  
  for (let i = 0; i < maxAttempts; i++) {
    try {
      const data = await fetchTaskAPI.getTaskStatus(taskId)
      
      if (typeof data.success === 'boolean') {
        // 任务完成
        if (data.success) {
          const dup = typeof data.duplicateCount === 'number' ? data.duplicateCount : 0
          ElMessage.success(`【${taskName}】抓取完成，获取到 ${data.newsCount} 条新闻（重复 ${dup} 条）`)
        } else {
          ElMessage.error(`【${taskName}】抓取失败: ${data.errorMessage || '未知错误'}`)
        }
        return
      }
      
      // 任务还在执行中，等待后继续查询
      await new Promise(resolve => setTimeout(resolve, interval))
      
    } catch (error) {
      console.error('查询任务状态失败:', error)
      await new Promise(resolve => setTimeout(resolve, interval))
    }
  }
  
  // 超时
  ElMessage.warning(`【${taskName}】抓取任务执行超时，请稍后查看结果`)
}

onMounted(reload)
</script>



